package filters;

import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.Enumeration;

/**
 * 获取 预检请求 的信息
 */
@Slf4j
public class OptionsFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
        log.info("OptionsFilter ___ init ___ 初始化过滤器");
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
        log.info("OptionsFilter ___ destroy ___ 销毁过滤器");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {
        log.info("OptionsFilter ___ doFilter ___ 进入了doFilter(预检查)");
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        log.info("OptionsFilter ___ doFilter ___ 进入了doFilter(预检查) ___ 请求地址是：{}", request.getRequestURL());

        // 判断是不是预检查
        String method = request.getMethod();
        if ("OPTIONS".equals(method)) {
            log.info("OptionsFilter ___ doFilter ___ 预检查查看请求参数：");
            Enumeration<String> headerNames = request.getHeaderNames();
            while (headerNames.hasMoreElements()) {
                String headerName = headerNames.nextElement();
                log.info("OptionsFilter ___ doFilter ___ 预检查查看请求参数 headerName是{}，参数内容是：{}", headerName, request.getHeader(headerName));
            }

            // 配置跨域
            HttpServletResponseHeaderConfig.setHttpServletResponseHeader(response);

            // 如果是预检查请求直接返回，不进入下一个过滤器
            return;
        }

        // 执行下一个过滤器
        filterChain.doFilter(request, response);
    }

}
